﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MINERP.MODEL.FoundationModel;
using MINERP.DAL;
using MINERP.COM;
using System.Data;
using MINERP.DAL.CommonDAL;

namespace MINERP.BLL.Statistics
{
    public class BillIndexBLL2
    {
        public delegate void ShowMsgEventHandler(int num, int type);//定义一个可以传递消息的委托
        public event ShowMsgEventHandler ShowMessage;

        public List<Shop_Info> GetShopInfoByHelpCode(string inHelpCode)
        {
            List<Shop_Info> shopInfoList = new List<Shop_Info>();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                List<Shop> listShop = db.Shop.Where(p => p.mnemonicCode.Contains(inHelpCode) && p.Status == 1).ToList();
                listShop.ForEach(s => shopInfoList.Add(new Shop_Info()
                {
                    Address = s.address,
                    Area = s.Area,
                    ShopKeeper = s.shopKeeper,
                    CreditLevel = s.CreditLevel ?? 0,
                    EmailAddr = s.EmailAddr,
                    MnemonicCode = s.mnemonicCode,
                    IsNeedPrintUPrice = s.IsNeedPrintUPrice ?? false,
                    MSN = s.MSN,
                    Tel1 = s.Tel1,
                    Tel2 = s.Tel2,
                    //PaperFaceID = s.PaperFaceId ?? 0,
                    //PaperTypeID = s.PaperTypeId ?? 0,

                    Salesman = s.Salesman,
                    Priority = s.Priority ?? 0,
                    QQ = s.QQ,
                    Remark = s.Remark,
                    ShopId = s.ShopId,
                    ShopName = s.shopName,
                    Status = s.Status ?? 0,


                }));

            }
            return shopInfoList;
        }
        public List<Shop_Info> GetShopInfoByFirstChar(string inHelpCode)
        {
            List<Shop_Info> shopInfoList = new List<Shop_Info>();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                List<Shop> listShop = db.Shop.Where(p => p.shopName.StartsWith(inHelpCode) && p.Status == 1).ToList();
                listShop.ForEach(s => shopInfoList.Add(new Shop_Info()
                {
                    Address = s.address,
                    Area = s.Area,
                    ShopKeeper = s.shopKeeper,
                    CreditLevel = s.CreditLevel ?? 0,
                    EmailAddr = s.EmailAddr,
                    MnemonicCode = s.mnemonicCode,
                    IsNeedPrintUPrice = s.IsNeedPrintUPrice ?? false,
                    MSN = s.MSN,
                    Tel1 = s.Tel1,
                    Tel2 = s.Tel2,
                    //PaperFaceID = s.PaperFaceId ?? 0,
                    //PaperTypeID = s.PaperTypeId ?? 0,

                    Salesman = s.Salesman,
                    Priority = s.Priority ?? 0,
                    QQ = s.QQ,
                    Remark = s.Remark,
                    ShopId = s.ShopId,
                    ShopName = s.shopName,
                    Status = s.Status ?? 0,


                }));

            }
            return shopInfoList;
        }
        public List<S_Bill_Info> GetShopBillInfo(DateTime inStartData, DateTime inEndDate, int inShopId, int inType)
        {
            int UnCheckOutInt = (int)ShopBillStatus.UnCheckOut;
            int CheckOutInt = (int)ShopBillStatus.CheckedOut;
            List<S_Bill_Info> listInfo = new List<S_Bill_Info>();
            int intPrintStatus = (int)Bill_Detail_Detail_Type.NeedStatArea;
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                List<SHOP_Bill> shopBill = null;
                if (inType == UnCheckOutInt)
                {
                    shopBill = db.SHOP_Bill.Where(p => p.CreateTime < inEndDate && p.CreateTime > inStartData && p.Shop.ShopId == inShopId && (p.Status == UnCheckOutInt)).ToList();
                }
                else if (inType == CheckOutInt)
                {
                    shopBill = db.SHOP_Bill.Where(p => p.CreateTime < inEndDate && p.CreateTime > inStartData && p.Shop.ShopId == inShopId && (p.Status == CheckOutInt)).ToList();
                }
                else
                {
                    shopBill = db.SHOP_Bill.Where(p => p.CreateTime < inEndDate && p.CreateTime > inStartData && p.Shop.ShopId == inShopId && (p.Status == CheckOutInt || p.Status == UnCheckOutInt)).ToList();
                }
                foreach (SHOP_Bill bill in shopBill)
                {
                    S_Bill_Info sbi = new S_Bill_Info();
                    sbi.BillId = bill.BillId;
                    sbi.BillOrderCode = bill.BillOrderCode;
                    sbi.CreateTime = bill.CreateTime;
                    sbi.TotalPrice = bill.TotalPrice ?? 0;
                    bill.Bill_Detail.Load();
                    foreach (Bill_Detail bdetail in bill.Bill_Detail)
                    {
                        bdetail.Bill_Detail_Detail.Load();
                    }
                    double PrintAreas = 0;
                    bill.Bill_Detail.ToList().ForEach(
                        b => { PrintAreas += b.Bill_Detail_Detail.Where(s => s.Type == intPrintStatus).Sum(pt => pt.Area); }
                        );
                    sbi.PrintAreas = (decimal)PrintAreas;
                    double PrintMoney = 0;
                    bill.Bill_Detail.ToList().ForEach(
                        d => { PrintMoney += d.Bill_Detail_Detail.Where(si => si.Type == intPrintStatus).Sum(pt => pt.Count); }
                        );
                    sbi.PrintMoney = (decimal)PrintMoney;
                    sbi.OtherMoney = (bill.TotalPrice ?? 0) - sbi.PrintMoney;
                    sbi.status = bill.Status;
                    listInfo.Add(sbi);

                }


            }
            return listInfo;

        }
        public SHOP_Bill_Info GetBillToView(int inBillID)
        {
            SHOP_Bill_Info sbi = new SHOP_Bill_Info();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                SHOP_Bill shopBill = db.SHOP_Bill.FirstOrDefault(p => p.BillId == inBillID);
                shopBill.ShopReference.Load();
                shopBill.Bill_Detail.Load();
                foreach (Bill_Detail bd in shopBill.Bill_Detail)
                {
                    bd.Bill_Detail_Detail.Load();
                }
                sbi.Shop = new Shop_Info() { Address = shopBill.Shop.address, Area = shopBill.Shop.Area, CreditLevel = (int)shopBill.Shop.CreditLevel, CreditLimit = (decimal)shopBill.Shop.CreditLimit, EmailAddr = shopBill.Shop.EmailAddr, IsNeedPrintUPrice = (bool)shopBill.Shop.IsNeedPrintUPrice, MSN = shopBill.Shop.MSN, QQ = shopBill.Shop.QQ, Salesman = shopBill.Shop.Salesman, ShopId = shopBill.Shop.ShopId, ShopName = shopBill.Shop.shopName, ShopKeeper = shopBill.Shop.shopKeeper, Tel1 = shopBill.Shop.Tel1, Tel2 = shopBill.Shop.Tel2 };
                sbi.List_Detail = new List<Bill_Detail_Info>();
                //shopBill.Bill_Detail.ToList().ForEach(
                //    p => { 
                //        sbi.List_Detail.Add(new Bill_Detail_Info(){BillDetailId=p.BillDetailId, CtmName=p.CtmName,

                //            ListDetail_Detail=new List<Bill_Detail_Detail_Info>(),

                //            OrderInfoCode=p.OrderInfoCode, OrderProductName=p.OrderProductName, Remark=p.OiRemark})
                //    }
                //    );
                foreach (Bill_Detail bd in shopBill.Bill_Detail)
                {
                    Bill_Detail_Info bdi = new Bill_Detail_Info();
                    bdi.BillDetailId = bd.BillDetailId;
                    bdi.CtmName = bd.CtmName;
                    bdi.OrderInfoCode = bd.OrderInfoCode;
                    bdi.OrderProductName = bd.OrderProductName;
                    bdi.Remark = bd.OiRemark;
                    bdi.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
                    foreach (Bill_Detail_Detail bdd in bd.Bill_Detail_Detail)
                    {
                        Bill_Detail_Detail_Info bddi = new Bill_Detail_Detail_Info() { Area = bdd.Area, Count = bdd.Count, DetailName = bdd.DetailName, Num = bdd.Num, Spec = bdd.Spec, Type = (int)bdd.Type, UnitPrice = bdd.UnitPrice, DetailRemark = bdd.DetailRemark };
                        bdi.ListDetail_Detail.Add(bddi);
                    }
                    sbi.List_Detail.Add(bdi);
                }
                sbi.BillCount = (double)shopBill.TotalPrice;
                sbi.ShopBalance = (double)shopBill.ShopBalance;
                sbi.CreateTime = shopBill.CreateTime;
                sbi.BillOrderCode = shopBill.BillOrderCode;
                sbi.BillId = shopBill.BillId;

            }
            return sbi;

        }
        /// <summary>
        /// 根据账单号获取账单列表
        /// </summary>
        /// <param name="inBillid"></param>
        /// <param name="ShopName"></param>
        /// <returns></returns>
        public List<S_Bill_Info> GetListByBillID(int inBillid, out string ShopName)
        {

            List<S_Bill_Info> rtnList = new List<S_Bill_Info>();
            int intPrintStatus = (int)Bill_Detail_Detail_Type.NeedStatArea;
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                //Shop shop = db.Shop.Where(p => p.SHOP_Bill.Where(pt => pt.Bill_Detail.FirstOrDefault(pi => pi.OrderInfoCode == inBarCode) != null) != null).FirstOrDefault();

                // SHOP_Bill sbill = db.SHOP_Bill.FirstOrDefault(p => p.Bill_Detail.FirstOrDefault(pt => pt.OrderInfoCode == inBarCode) != null);


                SHOP_Bill bill = db.SHOP_Bill.FirstOrDefault(sb => sb.BillId == inBillid);
                if (bill == null)
                {
                    ShopName = "";
                    return null;
                }
                bill.ShopReference.Load();
                S_Bill_Info sbi = new S_Bill_Info();
                sbi.BillId = bill.BillId;
                sbi.BillOrderCode = bill.BillOrderCode;
                sbi.CreateTime = bill.CreateTime;
                sbi.TotalPrice = bill.TotalPrice ?? 0;
                bill.Bill_Detail.Load();
                foreach (Bill_Detail bdetail in bill.Bill_Detail)
                {
                    bdetail.Bill_Detail_Detail.Load();
                }
                double PrintAreas = 0;
                bill.Bill_Detail.ToList().ForEach(
                    b => { PrintAreas += b.Bill_Detail_Detail.Where(s => s.Type == intPrintStatus).Sum(pt => pt.Area); }
                    );
                sbi.PrintAreas = (decimal)PrintAreas;
                double PrintMoney = 0;
                bill.Bill_Detail.ToList().ForEach(
                    d => { PrintMoney += d.Bill_Detail_Detail.Where(si => si.Type == intPrintStatus).Sum(pt => pt.Count); }
                    );
                sbi.PrintMoney = (decimal)PrintMoney;
                sbi.OtherMoney = (bill.TotalPrice ?? 0) - sbi.PrintMoney;
                sbi.status = bill.Status;
                rtnList.Add(sbi);
                ShopName = bill.Shop.shopName;
                return rtnList;

            }

        }

        public List<S_Bill_Info> GetListByBarCode(string inBarCode, out string ShopName)
        {
            List<S_Bill_Info> rtnList = new List<S_Bill_Info>();
            int intPrintStatus = (int)Bill_Detail_Detail_Type.NeedStatArea;
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                //Shop shop = db.Shop.Where(p => p.SHOP_Bill.Where(pt => pt.Bill_Detail.FirstOrDefault(pi => pi.OrderInfoCode == inBarCode) != null) != null).FirstOrDefault();

                // SHOP_Bill sbill = db.SHOP_Bill.FirstOrDefault(p => p.Bill_Detail.FirstOrDefault(pt => pt.OrderInfoCode == inBarCode) != null);
                Bill_Detail bDetail = db.Bill_Detail.FirstOrDefault(p => p.OrderInfoCode == inBarCode);
                if (bDetail == null)
                {
                    ShopName = "";
                    return null;

                }
                else
                {
                    bDetail.SHOP_BillReference.Load();
                    SHOP_Bill bill = bDetail.SHOP_Bill;
                    bill.ShopReference.Load();
                    S_Bill_Info sbi = new S_Bill_Info();
                    sbi.BillId = bill.BillId;
                    sbi.BillOrderCode = bill.BillOrderCode;
                    sbi.CreateTime = bill.CreateTime;
                    sbi.TotalPrice = bill.TotalPrice ?? 0;
                    bill.Bill_Detail.Load();
                    foreach (Bill_Detail bdetail in bill.Bill_Detail)
                    {
                        bdetail.Bill_Detail_Detail.Load();
                    }
                    double PrintAreas = 0;
                    bill.Bill_Detail.ToList().ForEach(
                        b => { PrintAreas += b.Bill_Detail_Detail.Where(s => s.Type == intPrintStatus).Sum(pt => pt.Area); }
                        );
                    sbi.PrintAreas = (decimal)PrintAreas;
                    double PrintMoney = 0;
                    bill.Bill_Detail.ToList().ForEach(
                        d => { PrintMoney += d.Bill_Detail_Detail.Where(si => si.Type == intPrintStatus).Sum(pt => pt.Count); }
                        );
                    sbi.PrintMoney = (decimal)PrintMoney;
                    sbi.OtherMoney = (bill.TotalPrice ?? 0) - sbi.PrintMoney;
                    sbi.status = bill.Status;
                    rtnList.Add(sbi);
                    ShopName = bill.Shop.shopName;
                    return rtnList;
                }
            }
        }
        //
        /// <summary>
        /// 获取客户选择时间内的账单并打印在一张上面
        /// </summary>
        /// <param name="inStartData"></param>
        /// <param name="inEndDate"></param>
        /// <param name="inShopId"></param>
        /// <returns></returns>
        public DataSet GetAllBillByDateAndid(DateTime inStartData, DateTime inEndDate, int inShopId)
        {
            string strGetSql = "select shop_bill.Billid,createtime,BillOrderCode,status,totalprice,Bill_Detail.BillDetailId,orderinfocode,orderproductName,ctmName,detailName,spec,num,unitprice,count,area,Type,DetailRemark from shop_bill,Bill_Detail,Bill_Detail_Detail" +
 " where shop_bill.BillId=Bill_Detail.BillId " +
 " and (shop_bill.status=0 or shop_bill.status=1) " +
" and Bill_Detail.BillDetailId=Bill_Detail_Detail.BillDetailId" +
" and shop_bill.shopid=" + inShopId + " and shop_bill.createtime between  '" + inStartData + "' and '" + inEndDate + "' order by Bill_Detail.Billid,orderinfocode,Bill_Detail.BillDetailId";


            return CommOperDB.ExceSQLDataSet(strGetSql);

        }
        //
        /// <summary>
        /// 获取客户选择时间内的账单并打印在一张上面(不带明细）
        ///)
        /// </summary>
        /// <param name="inStartData"></param>
        /// <param name="inEndDate"></param>
        /// <param name="inShopId"></param>
        /// <returns></returns>
        public DataSet GetAllBillIndexByDateAndid(DateTime inStartData, DateTime inEndDate, int inShopId)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append(" select b.Billid,b.createtime,b.orderinfocode,b.orderproductName,b.ctmName,b.totalprice,b.BillOrderCode, a.productprice ");
            sql.Append(" from ");
            sql.Append(" (select ");
            sql.Append(" sum(count) productprice,BillDetailId  ");
            sql.Append(" from  ");
            sql.Append(" dbo.Bill_Detail_Detail   ");
            sql.Append(" group by BillDetailId  ");
            sql.Append(" ) a,  ");
            sql.Append(" (  ");
            sql.Append(" select  ");
            sql.Append("  shop_bill.Billid  ");
            sql.Append(" ,createtime  ");
            sql.Append("   ,BillOrderCode  ");
            sql.Append("   ,status  ");
            sql.Append("   ,totalprice ");
            sql.Append(" ,Bill_Detail.BillDetailId ");
            sql.Append("   ,orderinfocode ");
            sql.Append("   ,orderproductName ");
            sql.Append("  ,ctmName ");
            sql.Append("  from  ");
            sql.Append("     shop_bill  ");
            sql.Append("     ,Bill_Detail  ");
            sql.Append("      where   ");
            sql.Append("       shop_bill.BillId=Bill_Detail.BillId     ");
            sql.Append("      and (shop_bill.status=0 or shop_bill.status=1)  ");
            sql.Append("      and shop_bill.shopid=     " + inShopId);
            sql.Append("     and shop_bill.createtime between  '" + inStartData + "' and '" + inEndDate + "'");
            sql.Append("     ) b ");
            sql.Append("    where a.BillDetailId=b.BillDetailId  ");
            sql.Append("  order by b.Billid,b.BillDetailId  ");
            return CommOperDB.ExceSQLDataSet(sql.ToString());
        }
        /// <summary>
        /// 获取商户生产的输出类型
        /// </summary>
        /// <param name="inStartData"></param>
        /// <param name="inEndDate"></param>
        /// <param name="inShopId"></param>
        /// <returns></returns>
        public DataSet GetAllShopPrint(DateTime inStartData, DateTime inEndDate, int inShopId)
        {
            string strGetSql = "select CreateTime,OrderInfoCode,OrderProductName,CtmName,DetailName,UnitPrice,Count,Area" +
                               " from dbo.Bill_Detail,dbo.Bill_Detail_Detail,dbo.SHOP_Bill" +
                               " where type=1 " +
                                " and  dbo.Bill_Detail.BillDetailId=dbo.Bill_Detail_Detail.BillDetailId  " +
                                " and dbo.SHOP_Bill.BillId=Bill_Detail.BillId " +
                               " and shop_bill.shopid=" + inShopId + " and shop_bill.createtime between  '" + inStartData + "' and '" + inEndDate + "' order by Bill_Detail.Billid,Bill_Detail.BillDetailId";


            return CommOperDB.ExceSQLDataSet(strGetSql);

        }
        /// <summary>
        /// 获取某商户未生产完成的产品的总价值
        /// </summary>
        /// <param name="inStartData"></param>
        /// <param name="inEndDate"></param>
        /// <param name="inShopId"></param>
        /// <returns></returns>
        public SHOP_Bill_Info GetUnCompleteProductBillByShop(DateTime inStartData, DateTime inEndDate, int inShopId)
        {
            int Bill_Detail_Id = 1;     //用于报表中的关联ID
            double Bill_Price = 0;
            SHOP_Bill_Info sbInfo = null;
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {

                Shop curShop = db.Shop.FirstOrDefault(s => s.ShopId == inShopId);
                sbInfo = new SHOP_Bill_Info();
                sbInfo.List_Detail = new List<Bill_Detail_Info>();
                List<orderInfo> listOrder = db.orderInfo.Where(oi => oi.Tb_OrderBag.Shop.ShopId == inShopId && oi.status == 1 && oi.Tb_OrderBag.OrderTime < inEndDate && oi.Tb_OrderBag.OrderTime > inStartData).OrderBy(o => o.OrderProductId).ToList();
                ShowMessage(listOrder.Count, 0);
                int iCount = 0;//计数器
                foreach (var oi in listOrder)
                {
                    iCount++;
                    ShowMessage(iCount, 1);
                    decimal orderInfoPrice = 0;//此产品的真实价格
                    #region 加载数据库
                    if (!oi.Tb_ProductReference.IsLoaded)
                    {
                        oi.Tb_ProductReference.Load();
                    }
                    if (!oi.Tb_Product.tb_CostTypeReference.IsLoaded)
                    {
                        oi.Tb_Product.tb_CostTypeReference.Load();
                    }
                    if (!oi.Tb_Product.Tb_PorductCategoryReference.IsLoaded)
                    {
                        oi.Tb_Product.Tb_PorductCategoryReference.Load();
                    }
                    if (!curShop.Shop_Product_Price.IsLoaded)
                    {
                        curShop.Shop_Product_Price.Load();
                    }
                    if (!oi.photoInfo.IsLoaded)
                    {
                        oi.photoInfo.Load();
                    }
                    if (!oi.Tb_OrderBagReference.IsLoaded)
                    {
                        oi.Tb_OrderBagReference.Load();
                    }
                    string orderBagName = oi.Tb_OrderBag.BagName.Split('_')[0];

                    #endregion
                    Bill_Detail_Info dbinfo = new Bill_Detail_Info() { BillDetailId = Bill_Detail_Id, Remark = oi.Remark, OrderInfoCode = oi.OrderProductId.ToString(), OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, OrderBagName = orderBagName };
                    Bill_Detail_Id++;
                    dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
                    orderInfoPrice = MINERP.BLL.CustomerManage.BillBLL.GetOrderPrice(curShop, oi, db, dbinfo);//获取产品的价值


                    dbinfo.BillDetailId = Bill_Detail_Id;

                    sbInfo.List_Detail.Add(dbinfo);
                    Bill_Detail_Id++;
                    Bill_Price += (double)orderInfoPrice;

                    //记录帐单信息            

                    sbInfo.Shop = new Shop_Info() { Address = curShop.address, ShopId = curShop.ShopId, ShopKeeper = curShop.shopKeeper, ShopName = curShop.shopName, Tel1 = curShop.Tel1, Tel2 = curShop.Tel2, QQ = curShop.QQ, IsNeedPrintUPrice = curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice, Salesman = curShop.Salesman, CreditLevel = curShop.CreditLevel == null ? 0 : (int)curShop.CreditLevel, IsAssignByCustom = curShop.IsAssignByCustom };
                    sbInfo.ShopBalance = (double)curShop.Balance;//指商户的总共欠款额度(包括本帐单)
                    sbInfo.BillCount = Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                }
            }


            return sbInfo;
        }
    }



    public class S_Bill_Info
    {
        public int BillId { get; set; }
        public int BillOrderCode { get; set; }
        public DateTime CreateTime { get; set; }
        public decimal PrintAreas { get; set; }
        public decimal PrintMoney { get; set; }
        public decimal OtherMoney { get; set; }
        public decimal TotalPrice { get; set; }
        public int status { get; set; }
    }
}
